/**
 * @file 通知窗口 IPC 处理器
 * @description 渲染进程请求 -> 主进程创建/转发到独立通知窗口
 */

import { ipcMain, webContents } from 'electron'
import {
  clearNotificationWindow,
  getNotificationWindow,
  showNotificationWindow
} from '#/windows/notifications'
import { NOTIFICATION_WINDOW_CHANNELS } from '~shared/ipc-topic'

// 映射 action clickToken -> 发起渲染进程的 webContents.id，用于点击时回传
const actionTokenOwner = new Map<string, number>()

let registered = false

export function registerNotificationIpcHandlers() {
  if (registered) return
  registered = true

  // 显示一条通知（转发到独立通知窗口）
  ipcMain.handle(
    NOTIFICATION_WINDOW_CHANNELS.SHOW,
    async (evt, options: Notify.NotificationOptions) => {
      // console.log('[Notifications] 收到显示通知请求:', options)
      try {
        // 记录 action 的 clickToken -> 发起窗口 id，用于之后点击回传
        if ((options as any)?.actions?.length) {
          for (const a of (options as any).actions) {
            if (a && typeof a.clickToken === 'string' && a.clickToken) {
              actionTokenOwner.set(a.clickToken, evt.sender.id)
            }
          }
        }

        showNotificationWindow(options, evt.sender)
        return { success: true }
      } catch (error) {
        console.error('[Notifications] 显示通知失败:', error)
        return { success: false, error: (error as Error).message }
      }
    }
  )
  // 动作点击：由通知窗口（独立渲染进程）上报，主进程再回传给发起渲染器
  ipcMain.handle(
    NOTIFICATION_WINDOW_CHANNELS.ACTION_CLICK,
    async (_evt, payload: { clickToken: string }) => {
      try {
        const token = payload?.clickToken
        if (!token) return { success: false, error: 'empty token' }
        const originId = actionTokenOwner.get(token)
        if (!originId) return { success: false, error: 'unknown token' }
        const target = webContents.fromId(originId)
        if (!target || target.isDestroyed()) return { success: false, error: 'origin gone' }
        // 回传给发起渲染器，由其 notify.ts 中的 bridge 调用实际 onClick()
        target.send(NOTIFICATION_WINDOW_CHANNELS.ACTION_CLICK, { clickToken: token })
        actionTokenOwner.delete(token)
        return { success: true }
      } catch (error) {
        return { success: false, error: (error as Error).message }
      }
    }
  )

  // 清空通知
  ipcMain.handle(NOTIFICATION_WINDOW_CHANNELS.CLEAR, async () => {
    try {
      clearNotificationWindow()
      return { success: true }
    } catch (error) {
      return { success: false, error: (error as Error).message }
    }
  })

  // 预热窗口（可选）
  ipcMain.handle(NOTIFICATION_WINDOW_CHANNELS.WARMUP, () => {
    try {
      getNotificationWindow()
      return { success: true }
    } catch (error) {
      return { success: false, error: (error as Error).message }
    }
  })

  console.log('✅ 通知窗口 IPC 处理器已注册')
}
